/*
 * 
 */
package com.oniontech.stamptour;

import java.util.List;
import java.util.Locale;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.Application;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.oniontech.stamptour.common.database.DatabaseManager;
import com.oniontech.stamptour.common.lang.LOG;
import com.oniontech.stamptour.common.util.SharedPreperenceUtil;
import com.oniontech.stamptour.resuorce.BitmapManager;

// TODO: Auto-generated Javadoc
/**
 * The Class ApplicationManager.
 * 
 * @author limsy
 * @since 2013/09/04
 */
//@ReportsCrashes(
//        formKey = "",
//        formUri = "https://animaluv.cloudant.com/acra-stamptour/_design/acra-storage/_update/report",
//        reportType = org.acra.sender.HttpSender.Type.JSON,
//        httpMethod = org.acra.sender.HttpSender.Method.PUT,
//        formUriBasicAuthLogin="odsouldthushadenteresele",
//        formUriBasicAuthPassword="nkr3Vv5L3fBAGHAYm05XCxdD"
//		)
public class ApplicationManager extends Application
{

	/** The context. */
	public static ApplicationManager context = null;
	
	/**
	 * Instantiates a new application manager.
	 */
	public ApplicationManager()
	{
		context = this;
	}
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Application#onCreate()
	 */
	public void onCreate()
	{
//		ACRA.init(this);

		new Thread()
		{
			public void run()
			{
				initManager();
				m_bLoaded = true;
			}
		}.start();
//		PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
//		wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK
//				| PowerManager.ACQUIRE_CAUSES_WAKEUP, "My Tag");
//		wl.acquire();

        //- 이미지 로더 세팅
        DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
                .cacheInMemory(true)
                .cacheOnDisc(true)
                .bitmapConfig(Bitmap.Config.RGB_565) // default
                .build();

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .memoryCacheSize(2 * 1024 * 1024)
                .denyCacheImageMultipleSizesInMemory()
                .defaultDisplayImageOptions(defaultOptions)
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .discCacheSize(2 * 1024 * 1024)
                .discCacheFileCount(100)
                .writeDebugLogs()
                .build();

        ImageLoader.getInstance().init(config);
	}
	
	/**
	 * Instance.
	 *
	 * @return the application manager
	 */
	public static ApplicationManager Instance()
	{
		return context;
	}

	/**
	 * Gets the single instance of ApplicationManager.
	 *
	 * @return single instance of ApplicationManager
	 */
	public static ApplicationManager getInstance()
	{
		return context;
	}

	/**
	 * Inits the manager.
	 */
	public void initManager()
	{
		LOG.setHeader(getString(R.string.app_name), true, 3);

		setLang();

		m_BitmapMgr = BitmapManager.getInstance();
		m_BitmapMgr.setContext(getApplicationContext());

		m_DatabaseMgr = DatabaseManager.getInstance();
		m_DatabaseMgr.setDBFileCopy(getApplicationContext());

		m_SharedPreperence = SharedPreperenceUtil.getInstance();
		m_SharedPreperence.initContext(getApplicationContext());

	}

	/**
	 * Check app mgr loaded.
	 * 
	 * @return true, if successful
	 */
	public boolean checkAppMgrLoaded()
	{
		return m_bLoaded;
	}

	/**
	 * Destroy mnager.
	 */
	public void destroyMnager()
	{
		if (m_BitmapMgr != null)
		{
			m_BitmapMgr.destory();
			m_BitmapMgr = null;
		}

		if (m_DatabaseMgr != null)
		{
			m_DatabaseMgr.destory();
			m_DatabaseMgr = null;
		}

		if (m_SharedPreperence != null)
		{
			m_SharedPreperence.destroy();
			m_SharedPreperence = null;
		}

		requestKillProcess(getApplicationContext());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Application#onTerminate()
	 */
	public void onTerminate()
	{
		LOG.Log_DEV("ApplicationManager",
				"ApplicationManager onTerminate() call~!!");
	}

	/**
	 * Request kill process.
	 *
	 * @param context the context
	 */
	public void requestKillProcess(final Context context)
	{

		// #1. first check api level.
		int sdkVersion = Integer.parseInt(Build.VERSION.SDK);
		if (sdkVersion < 8)
		{
			// #2. if we can use restartPackage method, just use it.
			ActivityManager am = (ActivityManager) context
					.getSystemService(Context.ACTIVITY_SERVICE);
			am.restartPackage(getPackageName());
		} else
		{
			// #3. else, we should use killBackgroundProcesses method.
			new Thread(new Runnable()
			{
				public void run()
				{
					ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
					String name = getApplicationInfo().processName;
					// RunningServiceInfo si;

					// pooling the current application process importance
					// information.
					while (true)
					{
						List<RunningAppProcessInfo> list = am
								.getRunningAppProcesses();
						for (RunningAppProcessInfo i : list)
						{
							if (i.processName.equals(name) == true)
							{
								// #4. kill the process,
								// only if current application importance is
								// less than IMPORTANCE_BACKGROUND
								if (i.importance >= RunningAppProcessInfo.IMPORTANCE_BACKGROUND)
									am.restartPackage(getPackageName()); // simple
																			// wrapper
																			// of
																			// killBackgrounProcess
								else
									Thread.yield();
								break;
							}
						}
					}
				}
			}, "Process Killer").start();
		}
	}

	/**
	 * Sets the lang.
	 */
	public void setLang()
	{
		// ���� Ȯ��
		Locale l = getApplicationContext().getResources().getConfiguration().locale;
		String Lang = l.getCountry();

		if (Lang.equals("KR"))
		{
			m_Lang = 0;
		} else
		{
			m_Lang = 1;
		}
	}

	/**
	 * Gets the lang.
	 * 
	 * @return the lang
	 */
	public int getLang()
	{
		return m_Lang;
	}

	/** The m_ bitmap mgr. */
	private BitmapManager m_BitmapMgr;

	/** The m_ database mgr. */
	private DatabaseManager m_DatabaseMgr;

	/** The m_ shared preperence. */
	private SharedPreperenceUtil m_SharedPreperence;


	/** The m_b loaded. */
	private boolean m_bLoaded = false;

	/** The wl. */
//	private PowerManager.WakeLock wl;

	/** The m_ lang. */
	private int m_Lang = 0;
	// private UserKey m_UserKey;
	/** The m_uri result. */
	public Uri m_uriResult;

	/** The Constant m_strLogTag. */
	public static final String m_strLogTag = "prepaidpay";

	/** The Constant s_strLogTag. */
	public static final String s_strLogTag = "prepaidpayACNT";
}
